package com.lengyu.iottransfer.gateway.controller;

import com.lengyu.iottransfer.gateway.common.BaseConstant;
import com.lengyu.iottransfer.gateway.security.exception.TokenException;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status =  getStatus(request);
        ErrorAttributeOptions errorAttributeOptions = getErrorAttributeOptions(request, MediaType.ALL);
        Map<String, Object> body = getErrorAttributes(request, errorAttributeOptions);

        //自定义的错误信息类
        //status.value():错误代码，
        //body.get("message").toString()错误信息
        if (body.containsKey("message")&&!body.get("message").toString().isEmpty()) {
            //在这里可以进行更为详细的定制,当前项目的需求只是捕获Filter中的token解析异常
            String msg = body.get("message").toString();
            throw new TokenException(BaseConstant.Returns.TOKEN_PARSE_FAILED,msg);
        }
        else{
           return new ResponseEntity<>(body, status);
        }
    }

}
